/*
 * IsoManager - Manage isometric sprites(anything but the background tiles)
 *
 * Copyright 2007 James W. Hofmann
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

#if flash9
import flash.display.Sprite;
import flash.geom.Point;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.Lib;
#end

class IsoManager

{

	private static var ordering : Array <IsoBitmap> = new Array();
	private static var lastordering : Array <IsoBitmap> = ordering.copy();
	public static var sprite : Sprite = new Sprite();
	
	public static function add(nb : IsoBitmap)
	{
		sprite.addChild(nb);
		ordering.insert(0,nb);
	}

	public static function remove(nb : IsoBitmap)
	{
		sprite.removeChild(nb);
		ordering.remove(nb);
		nb.bitmapData.dispose();
		nb = null;
	}
	
	public static function up()
	{
		if (ordering!=lastordering)
			{
			ordering.sort(comparison);
			for (n in 0...ordering.length)
			{
				sprite.setChildIndex(ordering[n], n);
			}
			lastordering = ordering.copy();
		}
	}
	
	public static function start()
	{
		sprite.cacheAsBitmap = true;
		Lib.current.addChild(sprite);
	}
	
	public static function end()
	{
		for (n in 0...ordering.length)
		{
			try
			{
				remove(ordering[0]);
			}
			catch(foo : Dynamic)
			{}
		}
		ordering = new Array();
		lastordering = ordering.copy();
		Lib.current.removeChild(sprite);
	}
	
	public static function comparison(a,b: IsoBitmap) : Int
	{
		return a.sortsum-b.sortsum;
	}	

}
